#!/bin/awk -f 
BEGIN {
    print "start perf latency statistics"
}

{
    # 统计事件的次数并且统计每个事件的时间
    time[evcountmap[$2]++][$2]=$1
}

END {
    seq=0
    # 循环采集到的时间
    for(event in evcountmap)
    {
        if(seq==0)
        {
            printf "\t" event "--->"
        }
        else if(seq==length(evcountmap)-1)
        {
            printf event "\n" 
        }
        else
        {
            printf event "\t" event "--->"
        }
        seq++
        #print "event:" event " total count:" evcountmap[event]
    }

    # 循环采集到的事件链次数
    for (evcount in time)
    {
        #print evcount
        lastevtime=0
        # 循环每次事件链的事件
        for( event in time[evcount] )
        {
             evtime=time[evcount][event]
             if(lastevtime!=0)
             {
                 # 两次事件的时间差
                 timespan=evtime-lastevtime
                 # 时间差总计，算平均数
                 evspantimetol[event]+=timespan
                 # 时间差最大值
                 if(timespan>evspantimemax[event])
                 {
                    evspantimemax[event]=timespan
                 }
                 # 时间差最小值
                 if(evspantimemin[event]==0 || timespan<evspantimemin[event])
                 {
                    evspantimemin[event]=timespan
                 }
                 printf timespan
                 printf "\t"
             }
             else
             {
                 printf "\t"
             }
             lastevtime=time[evcount][event]
        
        }
        printf "\n"

    }
    
    # 计算平均数
    seq=0
    for(evspan in evspantimetol)
    {
        if(seq==0)
        {
            printf "avg:\t" evspantimetol[evspan]/length(time)
        }
        else
        {
            printf "\t" evspantimetol[evspan]/length(time)
        }
        seq=1
    }
    printf "\n"
    
    # 计算最大值
    seq=0
    for(evspan in evspantimemax)
    {
        if(seq==0)
        {
            printf "max:\t" evspantimemax[evspan]
        }
        else
        {
            printf "\t" evspantimemax[evspan]
        }
        seq=1
    }
    printf "\n"

    # 计算最小值
    seq=0
    for(evspan in evspantimemin)
    {
        if(seq==0)
        {
            printf "min:\t" evspantimemin[evspan]
        }
        else
        {
            printf "\t" evspantimemin[evspan]
        }
        seq=1
    }
    printf "\n"
}
